﻿using System;
using System.ComponentModel;
using System.IO;
using System.ServiceModel;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

using Microsoft.Phone.Tasks;

namespace GroupChallenge.PlayerAdminWP7
{
    public class PlayerPictureViewModel : INotifyPropertyChanged
    {
        #region Private Members

        private const double MaxImageDimension = 250.0;
        private byte[] PhotoBytes { get; set; }
        private const string DefaultHostServer = "LocalHost"; //DallasXaml.com;

        #endregion                              // Private Members

        #region Properties

        private int _PlayerId = 0;
        public int PlayerId
        {
            get { return _PlayerId; }
            set
            {
                _PlayerId = value;
                RaisePropertyChanged("PlayerId");
            }
        }

        private string _LastMessage = string.Empty;
        public string LastMessage
        {
            get { return _LastMessage; }
            set
            {
                _LastMessage = value;
                RaisePropertyChanged("LastMessage");
            }
        }

        private string _UploadServer = DefaultHostServer;
        public string UploadServer
        {
            get
            {
                // Get from Isolated storage.
                if (string.IsNullOrEmpty(_UploadServer))
                    _UploadServer = Utils.GetSetting("UploadServer");

                if (string.IsNullOrEmpty(_UploadServer))
                    _UploadServer = DefaultHostServer;

                return _UploadServer;
            }
            set
            {
                _UploadServer = value;

                // Set back to a default localhost.
                if (string.IsNullOrEmpty(_UploadServer))
                    _UploadServer = DefaultHostServer;

                Utils.SaveSetting("UploadServer", _UploadServer);

                RaisePropertyChanged("UploadServer");
            }
        }

        public BitmapImage Photo
        {
            get
            {
                if (PhotoBytes == null)
                    return null;

                BitmapImage image = new BitmapImage();
                image.SetSource(new MemoryStream(PhotoBytes));

                return image;
            }
        }

        #endregion                              // Properties

        #region NotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(String propertyName)
        {
            if (null != PropertyChanged)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion                              // NotifyPropertyChanged

        #region Internal Methods

        // Store the picture in the current photo bytes.
        internal void StorePicture(PhotoResult photoResult)
        {
            Stream photoStream = photoResult.ChosenPhoto;

            if (photoStream == null)
                return;

            BitmapImage image = new BitmapImage();
            image.SetSource(photoStream);

            double scale = Math.Min(MaxImageDimension / (double)image.PixelWidth, MaxImageDimension / (double)image.PixelHeight);
            MemoryStream photo = new MemoryStream();

            WriteableBitmap writeableBitmap = new WriteableBitmap(image);

            writeableBitmap.SaveJpeg(photo, (int)(image.PixelWidth * scale), (int)(image.PixelHeight * scale), 0, 80);

            photo.Flush();

            PhotoBytes = photo.GetBuffer();

            LastMessage = "Ready to upload picture...";

            // Fire change for the BitmapImage.
            RaisePropertyChanged("Photo");
        }

        // Send the current photo bytes to the server and show the new id of the file / player.
        internal void Upload(Dispatcher dispatcher)
        {
            if (null == PhotoBytes ||
                PhotoBytes.Length == 0)
            {
                LastMessage = "Ready to take a picture.";
                return;
            }

            LastMessage = "Uploading...";

            try
            {
                string endpointConfigurationName = "BasicHttpBinding_IPlayerAdminService";
                string endpointUrl = string.Format("http://{0}/GroupChallenge/PlayerAdminService.svc", UploadServer);
                EndpointAddress endpointAddress = new EndpointAddress(endpointUrl);

                PlayerAdminSvc.IPlayerAdminService playerAdminService = new PlayerAdminSvc.PlayerAdminServiceClient(endpointConfigurationName, endpointAddress);

                playerAdminService.BeginSavePlayerImage(PhotoBytes, (result) =>
                {
                    try
                    {
                        int newPlayerId = playerAdminService.EndSavePlayerImage(result);
                        dispatcher.BeginInvoke(() =>
                        {
                            PlayerId = newPlayerId;
                            LastMessage = String.Format("Player {0}", PlayerId);
                        });
                    }
                    catch (Exception ex)
                    {
                        LastMessage = ex.Message;
                    }
                }, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Uploading Picture. " + ex.Message, "Upload Error", MessageBoxButton.OK);

                LastMessage = "Error: " + ex.Message;
            }
        }

        #endregion                              // Internal Methods
    }
}
